package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author zhouwei
 * @date 2020-01-06 9:53
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private OrderService orderService;

    /**
     * 提交预约
     * @param map
     * @return
     */
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        //获取电话号码
        String telephone = (String) map.get("telephone");
        //获取redis验证码
        String redisCode = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        //获取用户填写的验证码
        String code = (String) map.get("validateCode");
        //校验成功
        if(code!=null&&redisCode!=null&&redisCode.equals(code)){
            Result result=null;
            try {
                map.put("orderType", Order.ORDERTYPE_WEIXIN);//设置预约方式
                result = orderService.order(map);

            if(result.isFlag()){//预约成功，发送短信通知
                SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
                String orderDate =(String) map.get("orderDate");
                String date = sd.format(DateUtils.parseString2Date(orderDate));
                SendSms.sendSms(telephone,SendSms.VALIDATE_CODE,date);
            }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }else{//验证码校验失败，
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }
    }


    @RequestMapping("/findById")
    public Result findById(Integer id){
        Map map= null;
        try {
            map = orderService.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
        return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
    }
}
